//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: '人生贵相知，何用金与钱',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    openid: '',

    imgUrls: [{
      img: "../../image/t1.jpg",
      openpath: ""
    },{
        img: "../../image/t2.jpg",
        openpath: ""
    },{
        img: "../../image/t3.jpg",
        openpath: ""
    },{
        img: "../../image/t4.jpg",
        openpath: ""
    }],
    server: [
      {
        img: "../../image/hl.png",
        openpath: "../addINote/addINote",
        text: "日历计算"
      },
      {
        img: "../../image/sc.png",
        openpath: "../7wh/7wh",
        text: "7岁以下儿童发育参照标准"
      },
      {
        img: "../../image/remove.png",
        openpath: "../removeIPay/removeIPay",
        text: "移除消费记录"
      },
      {
        img: "../../image/clac.png",
        openpath: "../bCount/bCount",
        text: "按天数累计求和"
      }
      
    ],
    unserver: [

    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000
    

  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },


  onLoad: function () {

    //自己后台的接口地址，与静态数据路径，后台部分不提供啦, 数据格式基本是postdata一个json，返回一个json
    wx.setStorageSync("sURL", "https://www.XXXXX.com/web");
    wx.setStorageSync("appURL", "https://www.XXXXX.com/static/WebApp/yan");

    //获得用户信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
    }

    var that = this;

    if (this.data.canIUse && !that.data.hasUserInfo) {

      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
        // wx.setStorageSync("userInfo", res.userInfo);
        app.globalData.userInfo = res.userInfo;
        that.doLogin(that);
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo;
          // wx.setStorageSync("userInfo", res.userInfo);
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          });
          that.doLogin(that);
        }
      });
    };
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo;
    // wx.setStorageSync("userInfo", e.detail.userInfo);
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    });
    var that = this;
    that.doLogin(that);
  },

  isExist: function (id) {
    var i = false;
    var postObj = {
      "OPENID": "\"" + id + "\""
    };
    wx.request({
      url: wx.getStorageSync("sURL"),
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      data: {
        url: '/webUserView',
        postdata: JSON.stringify(postObj)
      },
      method: 'POST',
      success: res => {
        console.log(res);
        var str = res.data.result;
        var str2 = JSON.parse(str);
        var rw = str2["rows"];
        if (rw.length != 0) {
          i = true;
        }
      }
    });
    return i;
  },

  doLogin: function (that) {
    wx.login({
      success: function (res) {
        console.log("res.code=====" + res.code);
        if (res.code) {
          var postObj = {
            "js_code": res.code
          };
          //发起网络请求
          wx.request({
            url: wx.getStorageSync("sURL"),
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            data: {
              url: '/weixin/jscode2session',
              postdata: JSON.stringify(postObj)
            },
            success: function (res) {
              var json = JSON.parse(res.data.result);
              wx.setStorageSync("openid", json.openid)
              console.log("openid=====" + json.openid);

              if (json.openid != '') {
                //检查是否存在
                var postObj = {
                  "OPENID": "\"" + json.openid + "\""
                };
                wx.request({
                  url: wx.getStorageSync("sURL"),
                  header: {
                    'content-type': 'application/x-www-form-urlencoded' // 默认值
                  },
                  data: {
                    url: '/webUserView',
                    postdata: JSON.stringify(postObj)
                  },
                  method: 'POST',
                  success: res => {
                    console.log(res);
                    var str = res.data.result;
                    var str2 = JSON.parse(str);
                    var rw = str2["rows"];
                    if (rw.length != 0) {
                      //更新用户
                      var postObj = {
                        "ID": json.openid,
                        "NICKNAME": that.data.userInfo.nickName,
                        "CITY": that.data.userInfo.city,
                        "COUNTRY": that.data.userInfo.country,
                        "PROVINCE": that.data.userInfo.province,
                        "AVATARURL": that.data.userInfo.avatarUrl
                      };
                      console.log(JSON.stringify(postObj));
                      wx.request({
                        url: wx.getStorageSync("sURL"),
                        header: {
                          'content-type': 'application/x-www-form-urlencoded' // 默认值
                        },
                        data: {
                          url: '/webUserUpdate',
                          postdata: JSON.stringify(postObj)
                        },
                        method: 'POST',
                        success: res => {
                          console.log(res);
                          // wx.showToast({
                          //   title: '添加成功',
                          //   icon: 'none',
                          //   duration: 500,
                          //   mask: true,
                          //   success: function () {
                          //   }
                          // });
                        },
                        fail: res => {
                          console.log(res);
                          // wx.showToast({
                          //   title: '添加失败',
                          //   icon: 'none',
                          //   duration: 1000
                          // });
                        }
                      })
                    } else {
                      //添加用户
                      var postObj = {
                        "ID": json.openid,
                        "OPENID": json.openid,
                        "DIARY_GROUP": json.openid,
                        "NICKNAME": that.data.userInfo.nickName,
                        "CITY": that.data.userInfo.city,
                        "COUNTRY": that.data.userInfo.country,
                        "PROVINCE": that.data.userInfo.province,
                        "AVATARURL": that.data.userInfo.avatarUrl
                      };
                      console.log(JSON.stringify(postObj));
                      wx.request({
                        url: wx.getStorageSync("sURL"),
                        header: {
                          'content-type': 'application/x-www-form-urlencoded' // 默认值
                        },
                        data: {
                          url: '/webUserAdd',
                          postdata: JSON.stringify(postObj)
                        },
                        method: 'POST',
                        success: res => {
                          console.log(res);
                          // wx.showToast({
                          //   title: '添加成功',
                          //   icon: 'none',
                          //   duration: 500,
                          //   mask: true,
                          //   success: function() {}
                          // });
                        },
                        fail: res => {
                          console.log(res);
                          wx.showToast({
                            title: '识别用户失败',
                            icon: 'none',
                            duration: 500
                          });
                        }
                      })
                    }
                  }
                });
              };
            }
          })
        } else {
          console.log('获取用户登录状态失败！' + res.errMsg)
        }
      }
    });
  }
})